import { AxiosError } from "axios";
import axiosInstance from "./axiosInstance";
import TokenManager from "./tokenManager";
import { buildUrlWithPathVariables } from "./urlBuilder";
import { handleRequestError } from "./errorHandler"; //
import { Request, RequestConfig, Response, PathVariables } from "./types";

// 请求方法
const request: Request = async <
  T = any,
  D extends object = any,
  Q extends object = any,
  U extends string = string,
  P = PathVariables<U>
>({
  url,
  method,
  data,
  params,
  pathVariables,
  ignoreAuth = false,
  silentError = false,
  throwError = false,
}: RequestConfig<D, Q, U, P>): Promise<Response<T>> => {
  const headers: Record<string, string> = {};
  // 如果需要 token，添加到请求头中
  if (!ignoreAuth) {
    const token = TokenManager.getToken();
    if (token) {
      headers["Authorization"] = `Bearer ${token}`;
    }
  }
  try {
    const response = await axiosInstance.request<T>({
      url: buildUrlWithPathVariables(url, pathVariables),
      method,
      data,
      params,
      headers,
    });

    return { success: true, data: response.data };
  } catch (error) {
    // 处理请求错误;也可以交给axios的拦截器处理
    const err = error as AxiosError;
    const response = await handleRequestError(err, {
      url,
      method,
      data,
      params,
      pathVariables,
      ignoreAuth,
      silentError,
      throwError,
    });

    if (throwError) throw new Error(response.errorMessage);
    return response;
  }
};

export default request;
